﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;


namespace Mystery.SharePoint.Layouts
{
	public partial class SPSiteMetadata : LayoutsPageBase
	{
		
		protected void Page_Load(object sender, EventArgs e)
		{
			SPSite site = SPContext.Current.Site;
			if (this.IsPostBack == false)
			{
				SiteMetadata metadata = site.GetMetadata<SiteMetadata>();
				if (metadata != null)
				{
					OwnerEditor.CommaSeparatedAccounts = metadata.Owner;
					if (string.IsNullOrEmpty(OwnerEditor.CommaSeparatedAccounts) == true)
					{
						OwnerEditor.CommaSeparatedAccounts = site.Owner.LoginName;
					}

					foreach (Control c in this.AdditionalMetadata.Controls)
					{
						ISiteMetadataControl mc = c as ISiteMetadataControl;
						if (mc != null)
						{
							mc.UpdateControls(metadata);
						}
					}
				}
			}
		}

		protected void BtnOK_Clicked(object sender, EventArgs e)
		{
			SPSite site = SPContext.Current.Site;

			base.Validate();
			if (base.IsValid == false) return;

			SiteMetadata metadata = site.GetMetadata<SiteMetadata>();
			if (metadata != null)
			{
				metadata.Owner = OwnerEditor.CommaSeparatedAccounts;

				foreach (Control c in this.AdditionalMetadata.Controls)
				{
					ISiteMetadataControl mc = c as ISiteMetadataControl;
					if (mc != null)
					{
						mc.UpdateMetadata(metadata);
					}
				}
				metadata.Update();
			}

			site.Features.Deactivate(FeatureName.MetadataRedirect);
			
			if (base.Request.QueryString["First"] == "1")
			{
                this.ToCustomPage(SPContext.Current.Web.Url);
			}
			else
			{
                this.ToSettingsPage();
			}
		}

		protected void CancelButtonClick(object sender, EventArgs e)
		{
            this.ToSettingsPage();
		}
	}
}
